{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. Let's make it more idiomatic"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Your task is to refactor the following report generation code to more idiomatic. The existing implementation was written by an unknown developer who did not know anything about the idioms of Python. Luckily the unkown developer documented the implementation decently and wrote some tests for it. \n",
    "\n",
    "### The specification of the report generation\n",
    "\n",
    "This file content:\n",
    "```\n",
    "something\n",
    "1\n",
    "7\n",
    "somEThing\n",
    "\n",
    "2\n",
    "wassup\n",
    "woop\n",
    "woop\n",
    "something\n",
    "WoOP\n",
    "```\n",
    "\n",
    "Should yield this report:\n",
    "```\n",
    "missing values: 1\n",
    "highest number: 7.0\n",
    "most common words: something, woop\n",
    "occurrences of most common: 3\n",
    "#####\n",
    "numbers: [1.0, 7.0, 2.0]\n",
    "words: ['something', 'something', 'wassup', 'woop', 'woop', 'something', 'woop']\n",
    "```\n",
    "\n",
    "Note:\n",
    "* all numbers of the input file should be presented as floats in the report\n",
    "* all words are presented as lowercased in the report\n",
    "* while calculating the most common words, the count should be done as case insensitive (in other words, `'WoOp'` should be considered the same word as `'woop'`)\n",
    "* if there are multiple different most common words, they should be presented in the format presented above\n",
    "* there are more examples in the tests\n",
    "\n",
    "Run the cell of the existing implementation and then run the tests to verify that it works correctly. Then make sure that you understand how the legacy implementation works. After that, start refactoring, a function by function. Good luck!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "editable": false
   },
   "outputs": [],
   "source": [
    "def get_report(path):\n",
    "    \"\"\"\n",
    "    Creates a report of the file specified as argument.\n",
    "\n",
    "    :param path: path to file from which the report should be created (string)\n",
    "    :return: the report (string)\n",
    "    \"\"\"\n",
    "    data = _read_file(path)\n",
    "    missing_count = data[0]\n",
    "    numbers = data[1]\n",
    "    words = data[2]\n",
    "    report = _make_report(missing_count, numbers, words)\n",
    "    return report\n",
    "\n",
    "\n",
    "def _read_file(path):\n",
    "    \"\"\"\n",
    "    Reads and returns the data from the file specified as argument.\n",
    "\n",
    "    :param path: path to the file to be read.\n",
    "    :return: a tuple containing\n",
    "    1. the number of empty lines (int)\n",
    "    2. numeric values (list of floats)\n",
    "    3. non-numeric values (list of strings)\n",
    "    \"\"\"\n",
    "    data_file = open(path, 'r')\n",
    "    lines = data_file.readlines()\n",
    "    line_count = len(lines)\n",
    "    idx = 0\n",
    "    empty_lines = 0\n",
    "    words = []\n",
    "    numbers = []\n",
    "    while idx < line_count:\n",
    "        line = lines[idx]\n",
    "        line = line.strip()\n",
    "        if line == '':\n",
    "            empty_lines = empty_lines + 1\n",
    "        else:\n",
    "            is_number = False\n",
    "            try:\n",
    "                number = float(line)\n",
    "                is_number = True\n",
    "            except Exception:\n",
    "                pass\n",
    "\n",
    "            if is_number:\n",
    "                numbers.append(number)\n",
    "            else:\n",
    "                words.append(line)\n",
    "        idx = idx + 1\n",
    "    data_file.close()\n",
    "\n",
    "    return empty_lines, numbers, words\n",
    "\n",
    "\n",
    "def _make_report(missing_values, numbers, words):\n",
    "    \"\"\"\n",
    "    Creates and a report based on data given as arguments.\n",
    "\n",
    "    :param missing_values: number of empty lines (int)\n",
    "    :param numbers: numeric values (list of floats)\n",
    "    :param words: non numeric values (list of strings)\n",
    "    :return: the generated report (string)\n",
    "    \"\"\"\n",
    "    max_value = _get_max_value(numbers)\n",
    "    lower_case_words = _words_to_lowercase(words)\n",
    "    most_common_info = _get_most_common_words(lower_case_words)\n",
    "    most_common_words = most_common_info[0]\n",
    "    most_common_count = most_common_info[1]\n",
    "\n",
    "    most_common_str = ''\n",
    "    for idx in range(len(most_common_words)):\n",
    "        most_common_str += most_common_words[idx] + ', '\n",
    "    # remove the last comma and space\n",
    "    most_common_str = most_common_str[0:len(most_common_str) - 2]\n",
    "\n",
    "    report = ('missing values: {}\\n'\n",
    "              'highest number: {}\\n'\n",
    "              'most common words: {}\\n'\n",
    "              'occurrences of most common: {}\\n'\n",
    "              '#####\\n'\n",
    "              'numbers: {}\\n'\n",
    "              'words: {}').format(missing_values, max_value, most_common_str,\n",
    "                                  most_common_count, numbers, lower_case_words)\n",
    "\n",
    "    return report\n",
    "\n",
    "\n",
    "def _get_max_value(numbers):\n",
    "    \"\"\"\n",
    "    Returns the greatest value of the list given as argument.\n",
    "\n",
    "    :param numbers: numbers (list of numeric values)\n",
    "    :return: greatest value of numbers, None if numbers is an empty list\n",
    "    \"\"\"\n",
    "    max_value = None\n",
    "    if len(numbers) > 0:\n",
    "        max_value = numbers[0]\n",
    "        for idx in range(len(numbers)):\n",
    "            if numbers[idx] > max_value:\n",
    "                max_value = numbers[idx]\n",
    "    return max_value\n",
    "\n",
    "\n",
    "def _words_to_lowercase(words):\n",
    "    \"\"\"\n",
    "    :param words: words to be converted (list of strings)\n",
    "    :return: lowercased words (list of strings)\n",
    "    \"\"\"\n",
    "    lowercased = []\n",
    "    for idx in range(len(words)):\n",
    "        value = words[idx].lower()\n",
    "        lowercased.append(value)\n",
    "    return lowercased\n",
    "\n",
    "\n",
    "def _get_most_common_words(words):\n",
    "    \"\"\"\n",
    "    Finds the most common words in a list of words.\n",
    "    If there are multiple different words with the same amount of occurrences,\n",
    "    they are all included in the return value sorted alphabetically.\n",
    "    In addition to returning the most common words, the return value\n",
    "    includes also the count of occurrences of the most common words.\n",
    "\n",
    "    :param words: list of words (list of strings)\n",
    "    :return: a tuple containing:\n",
    "    1. most common words (list of strings)\n",
    "    2. the count of occurrences of the most common words (int)\n",
    "    \"\"\"\n",
    "    word_counts = {}\n",
    "    idx = 0\n",
    "    while idx < len(words):\n",
    "        value = words[idx]\n",
    "        if value not in word_counts.keys():\n",
    "            word_counts[value] = 1\n",
    "        else:\n",
    "            word_counts[value] += 1\n",
    "        idx = idx + 1\n",
    "\n",
    "    max_count = 0\n",
    "    for value in word_counts.values():\n",
    "        if value > max_count:\n",
    "            max_count = value\n",
    "\n",
    "    most_common_words = []\n",
    "    for word in word_counts.keys():\n",
    "        count = word_counts[word]\n",
    "        if count == max_count:\n",
    "            most_common_words.append(word)\n",
    "\n",
    "    most_common_words = sorted(most_common_words)\n",
    "\n",
    "    return most_common_words, max_count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now it's time refactor the existing code to make it more idiomatic.\n",
    "\n",
    "It's desirable that you do the refactoring in small chunks. Consider using the following workflow:\n",
    "1. Copy-paste a single function from the above ugly implementation to the cell below\n",
    "2. Refactor the function\n",
    "3. Run the tests to verify that you did not break anything\n",
    "\n",
    "This way you can consider each function as a separate sub task."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Your beautiful refactored, idiomatic, pythonic solution here\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The tests are here. Run these often while refactoring!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "editable": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "CURRENT_DIR = os.getcwd()\n",
    "DATA_DIR = os.path.join(os.path.dirname(CURRENT_DIR), 'data')\n",
    "\n",
    "DATA_FILE1 = os.path.join(DATA_DIR, 'misc_data1.txt')\n",
    "DATA_FILE2 = os.path.join(DATA_DIR, 'misc_data2.txt')\n",
    "DATA_FILE3 = os.path.join(DATA_DIR, 'empty.txt')\n",
    "\n",
    "expected1 = '''missing values: 2\n",
    "highest number: 99.0\n",
    "most common words: john\n",
    "occurrences of most common: 4\n",
    "#####\n",
    "numbers: [1.0, 2.0, 99.0, 6.72, 2.0, 2.0, 2.0]\n",
    "words: ['john', 'doe', 'john', 'john', 'was', 'here', 'this', 'is', 'totally', 'random', 'john']'''\n",
    "\n",
    "expected2 = '''missing values: 3\n",
    "highest number: 101.0\n",
    "most common words: doe, john\n",
    "occurrences of most common: 4\n",
    "#####\n",
    "numbers: [1.0, 2.0, 101.0, 6.72, 2.0, 2.0, 67.0, 2.0]\n",
    "words: ['john', 'doe', 'john', 'john', 'doe', 'was', 'doe', 'here', 'this', 'is', 'totally', 'random', 'john', 'doe']'''\n",
    "\n",
    "expected3 = '''missing values: 0\n",
    "highest number: None\n",
    "most common words: \n",
    "occurrences of most common: 0\n",
    "#####\n",
    "numbers: []\n",
    "words: []'''\n",
    "\n",
    "assert get_report(DATA_FILE1) == expected1\n",
    "print('First one OK!')\n",
    "\n",
    "assert get_report(DATA_FILE2) == expected2\n",
    "print('Second one OK!')\n",
    "\n",
    "assert get_report(DATA_FILE3) == expected3\n",
    "print('All OK, woop woop!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If the tests are failing, you can debug here.\n",
    "\n",
    "report = get_report(DATA_FILE1)\n",
    "print(report)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
